package cn.apptec.test.interview;

import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

public class ChangeFinalWrap {

    //包装类才能被修改
    private static final Integer age = 32;
    //字符串常量和基本类型不能被修改
    private static final int score = 32;


    @Test
    public void testChangeWrap() throws Exception {
        Field ageField = ChangeFinalWrap.class.getDeclaredField("age");
        ageField.setAccessible(Boolean.TRUE);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(Boolean.TRUE);
        modifiersField.setInt(ageField, ageField.getModifiers() & ~Modifier.FINAL);
        ageField.set(null, 22);
        assertThat("!!!", 22, equalTo(age));
    }


    @Test
    public void testChangeBasic() throws Exception {
        Field ageField = ChangeFinalWrap.class.getDeclaredField("score");
        ageField.setAccessible(Boolean.TRUE);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(Boolean.TRUE);
        modifiersField.setInt(ageField, ageField.getModifiers() & ~Modifier.FINAL);
        ageField.set(null, 22);
        assertThat("!!!", 32, equalTo(score));
    }

}